package com.hup.utils.swing.model;

import com.hup.utils.commons.hardware.ScreenUtilExtend;
import lombok.Data;

import javax.swing.*;
import java.awt.*;

/**
 * 窗口配置[位置(必须),置顶,状态(最大化/还原),大小]
 * @author hugan
 * @date 2019/12/6
 */
@Data
public class BaseWindowConfig {

    public Point loc;
    public Boolean alwaysOnTop;
    public Integer winState = Frame.NORMAL;
    /**
     * 使用Point是因为,处理fastJson在序列化Dimension时,会有StackOverflowError的问题!
     */
    public Point size;

    public void setSize(Point size) {
        this.size = size;
    }

    /**
     * 转化方法
     */
    public void setSize(Dimension size) {
        setSize(new Point((int) size.getWidth(), (int) size.getHeight()));
    }

    public void initFrame(JFrame frame) {
        //要先设置state(取值不影响size),再到size,这样才能在最大化还原后有大小!
        if (getWinState() != null && Toolkit.getDefaultToolkit().isFrameStateSupported(getWinState())) {
            //目前JDK不支持[竖直最大化]
            frame.setExtendedState(getWinState());
        }

        Point size = getSize();
        if (size != null) {
            frame.setSize(size.x, size.y);
        }

        if (getLoc() != null) {
            frame.setLocation(getLoc());
            //如果不在(多个)屏幕内,就居中显示
            Rectangle rect = new Rectangle(frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight());
            if (!ScreenUtilExtend.isInsideScreens(rect)) frame.setLocationRelativeTo(null);
        } else {
            frame.setLocationRelativeTo(null);
        }

        if (getAlwaysOnTop() != null) {
            frame.setAlwaysOnTop(getAlwaysOnTop());
        }
    }

    /**
     * 最大化的frame点击关闭按钮后,需要复用再次展示时,要重新加载配置;
     * 否则 显示后,下次还原最大化时丢失了[信息]
     */
    public void reInitOnReShow(JFrame frame) {
        if (frame.getExtendedState() == Frame.MAXIMIZED_BOTH) {
            frame.setLocation(getLoc());
            Point size = getSize();
            frame.setSize(size.x, size.y);
        }
    }

}
